package controller;

import com.alibaba.fastjson.JSON;
import org.apache.commons.beanutils.BeanUtils;
import services.DMLService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: personnel_management_system
 * @description: dml op
 * @author: Mr.Sun
 * @create: 2020-06-09 08:42
 **/
@WebServlet("/dml")
public class DMLSqlController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //拿到前端传来的JSON数据
        BufferedReader reader = req.getReader();
        String json = reader.readLine();
//        System.out.println(json);
        reader.close();
        //JSON字符串转换成Map对象
        Map<String,Object> map = JSON.parseObject(json, HashMap.class);
        String type = (String) map.remove("sqlType");
        String tableName = (String) map.remove("tableName");
        System.out.println("request："+map);

        resp.setContentType("text/json;charset=UTF-8");
        resp.setCharacterEncoding("UTF-8");
        PrintWriter out = resp.getWriter();
        Map<String,Object> mapOut = new HashMap<>();
        mapOut.put("result","false");
        try {
            Object obj = Class.forName("entity."+tableName).newInstance();
            BeanUtils.populate(obj,map);

            System.out.println(obj);
            DMLService dml = new DMLService();
            mapOut.put("result", dml.DMLExecute(type,tableName,obj));
        } catch (Exception e) {
            e.printStackTrace();
        }
        out.println(JSON.toJSONString(mapOut));
        out.flush();
        out.close();
    }
}
